<template>
  <div class="edituser-container">
    <el-form ref="formRef" :model="data.formData" label-width="80px">
      <el-form-item
        label="姓名"
        prop="name"
        :rules="[{ required: true, message: '请输入姓名' }]"
      >
        <el-input
          v-model="data.formData.name"
          placeholder="请输入姓名"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="账号"
        prop="account"
        :rules="[{ required: true, message: '请输入账号' }]"
      >
        <el-input
          v-model="data.formData.account"
          placeholder="请输入账号"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="角色"
        prop="role"
        :rules="[{ required: true, message: '请选择角色' }]"
      >
        <el-select v-model="data.formData.role" placeholder="请选择角色">
          <el-option label="管理员" value="管理员"></el-option>
          <el-option label="普通用户" value="普通用户"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="电话"
        prop="phone"
        :rules="[{ required: true, message: '请输入电话' }]"
      >
        <el-input
          v-model="data.formData.phone"
          placeholder="请输入电话"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="部门"
        prop="departmentId"
        :rules="[{ required: true, message: '请选择部门' }]"
      >
        <el-tree-select
          v-model="data.formData.departmentId"
          :data="data.departmentTrees"
          :props="{ label: 'name', value: 'id' }"
          @change="events.handleDepartmentChange"
          default-expand-all
          check-strictly
          :render-after-expand="false"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item
        label="职位"
        prop="jobId"
        :rules="[{ required: true, message: '请选择职位' }]"
      >
        <el-select
          v-model="data.formData.jobId"
          clearable
          placeholder="Select"
          style="width: 240px"
        >
          <el-option
            v-for="item in data.jobItems"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否禁用" prop="isActive">
        <el-switch
          v-model="data.formData.isActive"
          :active-value="1"
          :inactive-value="0"
          active-text="是"
          inactive-text="否"
          class="ml-2"
          style="--el-switch-on-color: #ff4949; --el-switch-off-color: #13ce66"
        />
      </el-form-item>
      <el-form-item
        label="用户头像"
        prop="avatar"
        :rules="[{ required: true, message: '请上传头像图片' }]"
      >
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          :action="baseUrl + '/User/UpdateWithImage'"
          v-model:file-list="data.avatarImages"
          :on-exceed="events.handleUploadExceed"
          :file-list-max-size="2 * 1024 * 1024"
          :data="data.formData"
          name="avatarImage"
          :on-success="events.handleOnSuccess"
          :on-error="events.handleOnError"
          :limit="1"
          :auto-upload="false"
          :headers="{
            Authorization: 'Bearer ' + getToken(),
          }"
        >
          <template v-if="data.formData.avatar">
            <el-image :src="data.avatarUrl" fit="contain"> </el-image>
          </template>
          <template v-else>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">无头像</div>
            <div class="el-upload__text">拖拽到此处或<em>点击上传</em></div>
          </template>
          <template #tip>
            <div class="el-upload__tip">
              上传头像图片大小不能超过 2M，且格式为 jpg、jpeg、png 等。
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <div class="btn-container">
      <el-button type="warning" @click="events.handleSubmit">修改</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { FormInstance } from 'element-plus';
import { onMounted, reactive, ref, watch } from 'vue';
import { getDeprtmentTree } from '../../../functions/department';
import { getUserDetail, updateUser } from '../../../functions/user';
import { useRoute } from 'vue-router';
import { getToken } from '../../../functions/token';
import { baseImagesUrl, baseUrl } from '../../../utils/request';
import { GetJobByDepartmentId } from '../../../functions/job';
import { toast } from '../../../utils/tools';

interface Data {
  formData: any;
  avatarUrl: string;
  avatarImages: any[];
  departmentTrees: any[];
  jobItems: any[];
}

const data = reactive<Data>({
  formData: {
    id: 0,
    name: '',
    account: '',
    role: '',
    avatar: '',
    password: '',
    salt: '',
    phone: '',
    jobId: '',
    isActive: false,
    isBan: false,
    departmentId: '',
  },
  avatarUrl: '',
  avatarImages: [],
  departmentTrees: [],
  jobItems: [],
});

const formRef = ref(null);
const uploadRef = ref(null);

watch(
  () => data.avatarImages,
  (newVal: any, oldVal: any) => {
    if (newVal.length > 0) {
      const file = newVal[0];
      const reader = new FileReader();
      reader.readAsDataURL(file instanceof File ? file : file.raw);
      reader.onload = (e: any) => {
        data.avatarUrl = e.target.result;
        data.formData.avatar = file.name;
      };
    } else {
      // 处理 newVal 为空的情况，例如重置 formData.avatar
      data.avatarUrl = '';
      data.formData.avatar = '';
    }
  },
  { deep: true }
);

const events = {
  async handleDepartmentChange(value: any) {
    const res = await GetJobByDepartmentId(value);
    if (res.code >= 0) {
      data.jobItems = res.data;
      data.formData.jobId = '';
    }
  },
  handleUploadExceed(newFiles: any, uploadFiles: any) {
    data.avatarImages = newFiles;
    return false;
  },
  handleReset() {
    const form = formRef.value as FormInstance | null;
    if (form) {
      form.resetFields();
      data.formData = {
        id: 0,
        name: '',
        account: '',
        role: '',
        avatar: '',
        password: '',
        salt: '',
        phone: '',
        jobId: '',
        isActive: false,
        isBan: false,
        departmentId: '',
      };
      data.avatarImages = [];
      data.avatarUrl = '';
    }
  },
  handleOnSuccess(res: any) {
    if (res.code >= 0) {
      toast.success(res.message || '修改成功');
      data.avatarImages = [];
    } else {
      toast.error(res.message || '修改失败');
    }
  },
  handleOnError(err: any) {
    toast.error(err.message || err || '上传失败');
  },
  handleSubmit() {
    const form = formRef.value as FormInstance | null;
    const upload = uploadRef.value as any;
    if (form && upload) {
      form
        .validate()
        .then(async (valid) => {
          if (valid) {
            // 提交表单
            if (data.avatarImages.length > 0) {
              upload.submit();
            } else {
              const res = await updateUser(data.formData);
              if (res.code >= 0) {
                toast.success(res.message || '修改成功');
              } else {
                toast.error(res.message || '修改失败');
              }
            }
          }
        })
        .catch((e) => {});
    }
  },
};
const route = useRoute();
onMounted(async () => {
  // 获取部门树
  const res = await getDeprtmentTree();
  if (res.code >= 0) {
    data.departmentTrees = res.data;
  }
  // 获取用户详情
  const id = Number(route.query.id);
  const res2 = await getUserDetail(id);
  if (res2.code >= 0) {
    data.formData = res2.data;
    data.avatarUrl = baseImagesUrl + res2.data.id + '/' + data.formData.avatar;
  }
  // 获取职位列表
  const departmentId = data.formData.departmentId;
  if (departmentId) {
    const res3 = await GetJobByDepartmentId(departmentId);
    if (res3.code >= 0) {
      data.jobItems = res3.data;
    }
  }
});
</script>

<style scoped lang="scss">
.edituser-container {
  padding: 20px;
  padding-bottom: 20%;
}
.btn-container {
  margin-top: 20px;
  text-align: right;
}
</style>
